package config

import (
	"example.com/myproject/project/global"
	"example.com/myproject/project/models"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
	"time"
)

// gorm 是默认开启事务的
func initDB() {
	db, err := gorm.Open(mysql.Open(AppConfig.Database.Dsn), &gorm.Config{})
	if err != nil {
		log.Fatalf("Error open mysql: %v", err)
	}
	sqlDB, _ := db.DB()
	sqlDB.SetMaxIdleConns(AppConfig.Database.MaxIdleConns)
	sqlDB.SetMaxOpenConns(AppConfig.Database.MaxOpenConns)
	sqlDB.SetConnMaxLifetime(time.Hour)
	fmt.Println("init database...")
	db.AutoMigrate(&models.User{})
	db.AutoMigrate(&models.ExchangeRate{})
	db.AutoMigrate(&models.Flight{})
	db.AutoMigrate(&models.Order{})
	db.AutoMigrate(&models.Aircraft{})
	db.AutoMigrate(&models.Passenger{})
	global.Db = db
}
